import { reqGetCakeList, reqGetCakeInfo } from '../../api/cate'
import { reqGetCateGoryList } from '../../api/category'
import { getStorage } from '../../utils/storage';
import { toast } from '../../utils/extendApi'
import {selectBuyCar,updateCount,deleteBuy,deletAllBuyApi} from '../../api/buycar'
Page({
  data: {
    show:false,//购物车列表是否显示
    isAllChecked:true,
    currentIndex: 0,
    currentCategory: null,
    categories: [], // 分类列表
    goodsList: [],    // 商品列表
    selectedCount: 0,    // 已选商品数量
    totalPrice: 0 ,       // 合计价格
    cartList: '',
    userinfo:'',
    iflogin:'',
  },
  //进入到支付页面
  checkout(){
    if(this.data.selectedCount==0){
      toast({ title: '请添加商品'});
      return
    }
    wx.navigateTo({
      url: '/pages/checkout/checkout',
    })
  },
  //清空
  buydel(){
    deletAllBuyApi(this.data.userinfo.userid);
    this.selectBuycarapi();
  },
  toggleCheck(e) {
    const id = e.currentTarget.dataset.id;
    let { cartList } = this.data;
    let selectedCount = 0;
    let totalPrice = 0;
    
    cartList = cartList.map(item => {
      if (item.id === id) {
        item.checked = !item.checked;
      }
      if (item.checked) {
        selectedCount++;
        totalPrice += item.price * item.count;
      }
      return item;
    });
    
    this.setData({
      cartList,
      selectedCount,
      totalPrice,
      isAllChecked: selectedCount === cartList.length
    });
  },

  // 切换全选
  toggleAllCheck() {
    const isAllChecked = !this.data.isAllChecked;
    let { cartList } = this.data;
    let selectedCount = 0;
    let totalPrice = 0;
    
    cartList = cartList.map(item => {
      item.checked = isAllChecked;
      if (isAllChecked) {
        selectedCount++;
        totalPrice += item.price * item.count;
      }
      return item;
    });
    
    this.setData({
      cartList,
      isAllChecked,
      selectedCount,
      totalPrice
    });
  },
  //修改购物车数量
   async updatecont(buycar){
     await updateCount(buycar);
  },
  //删除购物车
  async deleteBuybyid(buyid){
    await deleteBuy(buyid);
  },
  // 修改商品数量
  changeCount(e) {
    const { id, type } = e.currentTarget.dataset;
    let { cartList } = this.data;
    let selectedCount = 0;
    let totalPrice = 0;
    cartList = cartList.map(item => {
      if (item.id === id) {
        if (type === 'minus') {
          item.count--;
          if(item.count>0){
            const buycar={
              "buyid":item.id,
              "cakesum":item.count
              }
          this.updatecont(buycar);
          }else{
            //再减直接退出购物车好吧
            this.deleteBuybyid(item.id);
            this.selectBuycarapi();
          }
        } else if (type === 'plus') {
          if(item.count<3){
            item.count++;
          }
          const buycar={
          "buyid":item.id,
          "cakesum":item.count
          }
          this.updatecont(buycar);
        }
      }
      if (item.checked) {
        selectedCount++;
        totalPrice += item.price * item.count;
      }
      return item;
    });
    
    this.setData({
      cartList,
      selectedCount,
      totalPrice
    });
  },
  // 切换商品选中状态
  toggleCheck(e) {
    const id = e.currentTarget.dataset.id;
    let { cartList } = this.data;
    let selectedCount = 0;
    let totalPrice = 0;
    
    cartList = cartList.map(item => {
      if (item.id === id) {
        item.checked = !item.checked;
      }
      if (item.checked) {
        selectedCount++;
        totalPrice += item.price * item.count;
      }
      return item;
    });
    
    this.setData({
      cartList,
      selectedCount,
      totalPrice,
      isAllChecked: selectedCount === cartList.length
    });
  },
  //点击购物袋显示购物车
  showif(){
    if(!this.data.iflogin){
      //跳转到登录页面
      toast({ title: '登录过后再进行此操作',duration:500});
      setTimeout(() => {
        // 新增地址成功后，返回地址
        wx.switchTab({
          url: '/pages/owner/owner',
        })
      }, 700);
      return;
    }
    let show=this.data.show;
    if(show){
      show=false;
    }else{
      show=true;
    }
    this.setData({show});
  },
  //关闭购物车选项
  onClose() {
    this.setData({ show: false });
  },
// 计算合计价格和已选商品数量
calculateTotal() {
    let totalPrice = 0;
    let selectedCount = 0;
    this.data.goodsList.forEach(item => {
        if (item.quantity) {
            totalPrice += item.cakePrice * item.quantity;
            selectedCount += item.quantity;
        }
    });
    this.setData({
        totalPrice,
        selectedCount
    });
},
// 点击切换分类
  switchCategory(e) {
    const index = e.currentTarget.dataset.index;
    const category = this.data.categories[index];
    // 确认 category 的 ID 字段，比如是 `id` 或 `categoryId`
    const categoryid = category.categoryid; 
    this.setData({
      currentIndex: index,
      currentCategory: category
    });
    this.getGoodsByCategoryId(categoryid);
  },

  async getCategories() {
    try {
      const res = await reqGetCateGoryList();
      console.log("分类接口返回数据：", res); // 打印完整返回
      if (res && res.code === 200 && res.data && res.data.categoryList) {
        const categoryList = res.data.categoryList;
        console.log("分类列表数据：", categoryList); // 打印分类数组
        // 确认分类的 ID 字段，比如是 `id` 还是 `categoryId`
        if (categoryList.length > 0) {
          console.log("第一个分类的 categoryId：", categoryList[0].categoryid); 
        }
        this.setData({
          categories: categoryList,
          currentCategory: categoryList[0]
        });
        // 传递正确的 ID 字段
        this.getGoodsByCategoryId(categoryList[0].categoryid); 
      } else {
        throw new Error('分类数据异常');
      }
    } catch (err) {
      toast({ title: '分类加载失败', icon: 'none' });
      console.error(err);
    }
  },

  async getGoodsByCategoryId(categoryid) {
    try {
      const res = await reqGetCakeList(categoryid);
      console.log("这是根据分类id获取商品列表的数据：");
      console.log(res);
      if (res && res.code === 200 && res.data && res.data.cakeListByCategoryId) {
        this.setData({
          goodsList: res.data.cakeListByCategoryId
        });
      } else {
        throw new Error('商品数据异常');
      }
    } catch (err) {
      toast({ title: '商品加载失败', icon: 'none' });
      console.error(err);
    }
  },

  onLoad(options) {
    this.setData({
      userinfo: getStorage("userinfo"),
      iflogin:getStorage("iflogin"),
    })
    this.getCategories();
    //查询购物车
    this.selectBuycarapi();
  },
  //查询购物车以及结算的方法
  async selectBuycarapi(){
    //查询购物车
    const res= await selectBuyCar(this.data.userinfo.userid);
    this.setData({
      cartList:res.data.buycarRep,
    })
    this.initTotal();
  },
  //加载计算总金额
  initTotal() {
    let totalPrice = 0;
    let selectedCount = 0;
    this.data.cartList.forEach(item => {
      if(item.checked){
      totalPrice += item.price * item.count;
      selectedCount+=1;
      }
    });
    this.setData({
        totalPrice,
        selectedCount
    });
},
  onShow(){
      this.selectBuycarapi();
      this.setData({
        userinfo: getStorage("userinfo"),
        iflogin:getStorage("iflogin"),
      })
    }
  // 其他生命周期函数保持不变...
});